package com.ly.controller;

import com.ly.bean.EasybuyUser;
import com.ly.bean.EasybuyUserAddress;
import com.ly.bean.Result;
import com.ly.service.MailService;
import com.ly.service.UserService;
import com.ly.util.CookieUtil;
import com.ly.util.ExChangeNameUtil;
import com.ly.util.RoutingKeyUtil;
import com.ly.util.UuidUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 李岩
 * @date 2021/12/18-9:34
 * @describe
 */
@Controller
@RequestMapping("/user/")
public class UserController {
    private final Logger logger= LoggerFactory.getLogger(UserController.class);
    private UserController(){
        System.out.println("UserController   的controller层");
    }
    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;
    @Reference(url = "dubbo://localhost:20885")
    private MailService mailService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("login")
    public String loginUser(EasybuyUser easybuyUser,String yzm, Model model, HttpServletRequest request, HttpServletResponse response){
        try {
            logger.info("用户登录   "+easybuyUser);
            //如果easybuyUser.getLoginname()不为空  说明 用户是使用用户名登录
            EasybuyUser loginUser = userService.selectUserByName(easybuyUser.getLoginname());
            if (loginUser.getId()==null){
                model.addAttribute("msg","用户名不存在");
                return "login";
            }
            if (loginUser.getId()!=null && !loginUser.getPassword().equals(easybuyUser.getPassword())){
                model.addAttribute("msg","密码错误");
                return "login";
            }

            //邮箱登录
            if (yzm!=null &&!"".equals(yzm) && loginUser.getId()!=null){
                String yzmredis =(String) redisTemplate.boundValueOps(loginUser.getEmail()).get();
                System.out.println("yzmredis=  "+yzmredis+";  yzm= "+yzm);
                if (yzm.equals(yzmredis)){
                    //判断用户身份 1 表示未激活
                    if(loginUser.getStatus()==1){
                        model.addAttribute("msg","尊敬的用户，您需要通过邮箱激活才能享受更高的服务");
                        return "login";
                    }
                    //2 表示没有完善信息
                    if(loginUser.getStatus()==2){
                        model.addAttribute("msg","尊敬的用户，您需要完善信息才能享受更高的服务");
                        return "Member_User.html";
                    }

                    model.addAttribute("msg","登录成功");

                    //用户登录成功后把用户信息存到redis里
                    String uuid = UuidUtil.getUUID();
                    userService.saveLoginUserToRedis(loginUser,uuid);
                    //把身份标识传给客户端
                    CookieUtil.setCookie(request,response,"uuid",uuid);
                    return "redirect:/shop/showIndex";
                }
            }

            //判断用户身份 1 表示未激活
            if(loginUser.getStatus()==1){
                model.addAttribute("msg","尊敬的用户，您需要通过邮箱激活才能享受更高的服务");
                return "login";
            }
            //2 表示没有完善信息
            if(loginUser.getStatus()==2){
                model.addAttribute("msg","尊敬的用户，您需要完善信息才能享受更高的服务");
                return "Member_User.html";
            }
            model.addAttribute("msg","登录成功");

            //用户登录成功后把用户信息存到redis里
            String uuid = UuidUtil.getUUID();
            userService.saveLoginUserToRedis(loginUser,uuid);
            //把身份标识传给客户端
            CookieUtil.setCookie(request,response,"uuid",uuid);
            return "redirect:/shop/showIndex";

        } catch (Exception e) {
            logger.error("用户登录异常   "+e);

        }
        return "login";
    }
    @RequestMapping("createYzm")
    @ResponseBody
    public Result createYzm(String key){

        try {
            logger.info("发送验证码  "+key);
            //生成一个四位数验证码
            int yzm=(int) (Math.random()*8999+1000);
            //把验证码存到redis中设置时间60s
            redisTemplate.boundValueOps(key).set(yzm+"");
            redisTemplate.boundValueOps(key).expire(60,TimeUnit.SECONDS);
            //发送邮件
            String info="易买网的验证码  <h2>"+yzm+"</h2><br/>不要告诉别人";
            mailService.sendHtmlMail(key,"易买网验证码",info);
            System.out.println(info);
            return Result.getResult(true,200,"验证码发送成功",null);
        } catch (Exception e) {
            logger.info("发送验证码出现异常  "+e);
        }
        return Result.getResult(false,444,"网络问题请重试",null);

    }

    @RequestMapping("addUser")
    public String addUser(EasybuyUser user,String yzm, Model model, HttpSession session){
        logger.info("用户注册   "+user);
        try {
            String yzmredis =(String) redisTemplate.boundValueOps(user.getEmail()).get();
            System.out.println("yzmredis=  "+yzmredis+";  yzm= "+yzm);
            user.setUsername("");
            user.setLoginname("");
            user.setType(0);
            user.setSex(1);

            //用户名称注册
            if (yzm==null || yzm==""){
                System.out.println(1111);
                user.setStatus(1);
                int userid = userService.addUser(user);

                System.out.println("userid="+userid);
                user.setId(userid);
                String content="欢迎注册易买网，<a href='http://localhost:8092/user/active?uid="+userid+"'>激活</a>完毕后才能使用";
                HashMap<String, Object> map = new HashMap<>();
                map.put("user",user);
                map.put("content",content);
                rabbitTemplate.convertAndSend(ExChangeNameUtil.DIRECT_EXCHANGE_USER, RoutingKeyUtil.DIRECT_ROUTINGKEY_EMAIL,map);
                /*Result result = mailService.sendHtmlMail(user.getEmail(), "易买网激活码", content);
                System.out.println("result  "+result);
                session.setAttribute("result",result);*/
            }
            //邮箱注册
            if (yzm.equals(yzmredis)){
                System.out.println(2222);
                user.setStatus(2);
                userService.addUser(user);
                Result result = Result.getResult(true, 200, "注册成功", null);
                System.out.println("result  "+result);
                session.setAttribute("result",result);
            }
            return "redirect:/Login.html";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("active")
    public String active(Integer uid){
        logger.info("用户激活   "+uid);
        try {
            //根据用户id查询用户对象
            EasybuyUser user = userService.selectByPrimaryKey(uid);
            user.setStatus(2);  //已经激活 未完善信息
            System.out.println("激活  "+user.getId()+"   "+user.getStatus());
            userService.updateUser(user);
            return "redirect:/Login.html";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }



    @RequestMapping("verifyUserAddress")
    @ResponseBody
    public Result verifyUserAddress(String useraddress, @CookieValue(required = false) String uuid){
        System.out.println("useraddress=  "+useraddress);
        try {
            logger.info("添加新的收货地址");
            EasybuyUser loginUser = userService.findUserByRedis(uuid);
            EasybuyUserAddress userAddress = new EasybuyUserAddress();
            if (loginUser!=null){
                userAddress.setAddress(useraddress);
                userAddress.setUserid(loginUser.getId());
                userAddress.setCreatetime(new Date());
                //添加新的收货地址
                userService.addUserAddress(userAddress);
                return Result.getResult(true,200,"添加地址成功", userAddress);
            }
            return Result.getResult(false,222,"用户已掉线，请重新输入",null);
        } catch (Exception e) {
            logger.error("添加新的收货地址出现异常  "+e);
        }

        return Result.getResult(false,444,"添加地址失败",null);
    }

    //
    @RequestMapping("findLoginUser")
    @ResponseBody
    public Result findLoginUser(@CookieValue(required = false) String uuid){


            try {
                if (uuid!=null && !"".equals(uuid)){
                    EasybuyUser loginUser = userService.findUserByRedis(uuid);
                    return Result.getResult(true,200,"用户登录成功",loginUser);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        return Result.getResult(false,444,"用户未登录",null);
    }
}
